<template>
  <div class="app-container">
   <el-container>
      <el-aside width="200px" style="background-color: white;">
    <el-table
      style="border: none;"
      v-if="refreshTable"
      :data="type1List"
      row-key="itemTypeId"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      @row-click="handleCategoryClick" > <!-- 新增：点击分类行触发查询 -->
      <el-table-column  align="center" prop="itemTypeName" />
    </el-table>


      </el-aside>
      <el-main>
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="物料编码" prop="itemCode">
        <el-input
          v-model="queryParams.itemCode"
          placeholder="请输入产品物料编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物料名称" prop="itemName">
        <el-input
          v-model="queryParams.itemName"
          placeholder="请输入产品物料名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="批次号" prop="batchCode">
        <el-input
          v-model="queryParams.batchCode"
          placeholder="请输入批次号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仓库" prop="warehouseName">
        <el-input
          v-model="queryParams.warehouseName"
          placeholder="请输入仓库"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="库区" prop="locationName">
        <el-input
          v-model="queryParams.locationName"
          placeholder="请输入库区"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="库位" prop="areaName">
        <el-input
          v-model="queryParams.areaName"
          placeholder="请输入库位"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['stock:stock:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['stock:stock:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="stockList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="物料编码" align="center" prop="itemCode" />
      <el-table-column label="物料名称" align="center" prop="itemName" />
      <el-table-column label="规格型号" align="center" prop="specification" />
      <el-table-column label="在库数量" align="center" prop="quantityOnhand" />
      <el-table-column label="单位" align="center" prop="unitOfMeasure" />
      <el-table-column label="批次号" align="center" prop="batchCode" />
      <el-table-column label="仓库" align="center" prop="warehouseName" />
      <el-table-column label="库区" align="center" prop="locationName" />
      <el-table-column label="库位" align="center" prop="areaName" />
      <el-table-column label="入库时间" align="center" prop="recptDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.recptDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['stock:stock:edit']">修改</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改库存现有量对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
       <el-form ref="stockRef" :model="form" :rules="rules" label-width="80px">
        <el-col :span="10">
            <el-form-item label="仓库位置" >
              <el-cascader v-model="value1" :options="formattedOptions" :style="{width: '100%'}" placeholder="请选择仓库"
                clearable></el-cascader>
            </el-form-item>
        </el-col>
        <el-form-item label="在库数量" prop="quantityOnhand">
          <el-input v-model="form.quantityOnhand" placeholder="请输入在库数量" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
       </el-main>
      
    </el-container>
  </div>
</template>

<script setup name="Stock">
import { listStock,  addStock, updateStock,getStock } from "@/api/stock/stock"

const { proxy } = getCurrentInstance()

const stockList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

import {cang } from "@/api/issue/issue"
// 绑定的选中值（数组形式，存储各级选中的value）
const value1=ref([])
const options1=ref([])
//查询仓库
cangku()
function cangku(){
  const result=cang();
  result.then(res=>{
     options1.value=res.data  
  })
}
 // 转换后的数据（供级联选择器使用）
const formattedOptions = computed(() => {
  // 递归转换函数：将原始数据转为级联选择器格式
  const convert = (data) => {
    return data.map(item => {
      // 仓库级节点
      const warehouseNode = {
        value: item.warehouseId,  // 仓库ID作为value
        label: item.warehouseName, // 仓库名称作为label
        children: []
      };

      // 处理库区子节点
      if (item.storageLocationList && item.storageLocationList.length) {
        warehouseNode.children = item.storageLocationList.map(location => {
          const locationNode = {
            value: location.locationId,  // 库区ID作为value
            label: location.locationName, // 库区名称作为label
            children: []
          };

          // 处理库位子节点
          if (location.storageAreaList && location.storageAreaList.length) {
            locationNode.children = location.storageAreaList.map(area => ({
              value: area.areaId,  // 库位ID作为value
              label: area.areaName  // 库位名称作为label
            }));
          }

          return locationNode;
        });
      }

      return warehouseNode;
    });
  };
  // 调用转换函数处理原始数据
  return convert(options1.value);
});

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    itemCode: null,
    itemName: null,
    batchCode: null,
    warehouseName: null,
    locationName: null,
    areaName: null,
    itemTypeId: 1,  // 新增：用于存储选中的物料分类ID
  },
 
  rules: {
    itemId: [
      { required: true, message: "产品物料ID不能为空", trigger: "blur" }
    ],
    warehouseId: [
      { required: true, message: "仓库ID不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)


/** 查询库存现有量列表 */
function getList() {
  loading.value = true
  listStock(queryParams.value).then(response => {
    stockList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    materialStockId: null,
    itemTypeId: 1,
    itemId: null,
    itemCode: null,
    itemName: null,
    specification: null,
    unitOfMeasure: null,
    quantityOnhand:null,
    batchCode: null,
    warehouseId: null,
    warehouseCode: null,
    warehouseName: null,
    locationId: null,
    locationCode: null,
    locationName: null,
    areaId: null,
    areaCode: null,
    areaName: null,
    vendorId: null,
    vendorCode: null,
    vendorName: null,
    vendorNick: null,
    quantityOnhand: null,
    workorderId: null,
    workorderCode: null,
    recptDate: null,
    expireDate: null,
    attr1: null,
    attr2: null,
    attr3: null,
    attr4: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  }
  proxy.resetForm("stockRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  // 清除分类ID查询条件
  queryParams.value.itemTypeId = 1
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.materialStockId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

import { cang1,qu,wei} from "@/api/issue/issue"
/** 提交按钮 */
async function submitForm() {
  
  // 1. 从级联选择器中获取仓库/库区/库位ID（确保数组有值）
  if (!value1.value || value1.value.length < 3) {
    proxy.$modal.msgError("请完整选择仓库位置");
    return; // 未选择完整时终止提交
  }
  
  form.value.warehouseId = value1.value[0];
  form.value.locationId = value1.value[1];
  form.value.areaId = value1.value[2];
  
  try {
    // 2. 等待所有异步请求完成（关键！）
    const [r, r1, r2] = await Promise.all([
      cang1(form.value.warehouseId),    // 查仓库信息
      qu(form.value.locationId),        // 查库区信息
      wei(form.value.areaId)            // 查库位信息
    ]);
    
    // 3. 给表单赋值（此时接口已返回数据）
    form.value.warehouseId = r.data.warehouseId;
    form.value.warehouseCode = r.data.warehouseCode;
    form.value.warehouseName = r.data.warehouseName;
    form.value.locationId = r1.data.locationId;
    form.value.locationCode = r1.data.locationCode;
    form.value.locationName = r1.data.locationName;
    form.value.areaId = r2.data.areaId;
    form.value.areaCode = r2.data.areaCode;
    form.value.areaName = r2.data.areaName;

  proxy.$refs["stockRef"].validate(valid => {
    if (valid) {
      if (form.value.materialStockId != null) {
        updateStock(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addStock(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
  } catch (error) {
    // 捕获接口请求失败的情况
    console.error("获取仓库/库区/库位信息失败：", error);
    proxy.$modal.msgError("数据加载失败，请重试");
  }
}

/** 修改按钮操作 */
function handleUpdate(row) {
  console.log("库存");
  console.log(row);
  value1.value=[row.warehouseId,row.locationId,row.areaId]
  reset()
  const _materialStockId = row.materialStockId || ids.value
  getStock(_materialStockId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改库存现有量"
  })
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download('stock/stock/export', {
    ...queryParams.value
  }, `stock_${new Date().getTime()}.xlsx`)
}

getList()


//下拉表
import { listType1} from "@/api/type1/type1"

/** 新增：处理物料分类点击事件 */
function handleCategoryClick(row) {
  // 设置选中的分类ID到查询参数
  queryParams.value.itemTypeId = row.itemTypeId
  // 重置页码为1
  queryParams.value.pageNum = 1
  // 执行查询
  getList()
}


const type1List = ref([])
const isExpandAll = ref(true)
const refreshTable = ref(true)


const data1 = reactive({
  queryParams1: {
  },
})

const { queryParams1 } = toRefs(data1)

/** 查询物料分类列表 */
function getList1() {
  loading.value = true
  listType1(queryParams1.value).then(response => {
    type1List.value = proxy.handleTree(response.data, "itemTypeId", "parentTypeId")
    loading.value = false
  })
}
	
	
getList1()
</script>
